<?php

namespace addon\hotel\api\controller;

use app\api\controller\BaseApi;
use addon\hotel\model\HotelBrowse as HotelBrowseModel;

class Hotelbrowse extends BaseApi
{
    /**
     * 添加信息
     */
    public function add()
    {
        $token = $this->checkToken();
        if ($token[ 'code' ] < 0) return $this->response($token);
        $hotel_id = isset($this->params[ 'hotel_id' ]) ? $this->params[ 'hotel_id' ] : 0;
        if (empty($hotel_id)) {
            return $this->response($this->error('', '缺少参数酒店id'));
        }

        $goods_browse_model = new HotelBrowseModel();
        $data = [
            'member_id' => $token[ 'data' ][ 'member_id' ],
            'hotel_id' => $hotel_id,
        ];
        $res = $goods_browse_model->addBrowse($data);
        return $this->response($res);

    }

    /**
     * 删除信息
     */
    public function delete()
    {
        $token = $this->checkToken();
        if ($token[ 'code' ] < 0) return $this->response($token);

        $id = isset($this->params[ 'id' ]) ? $this->params[ 'id' ] : 0;
        if (empty($id)) {
            return $this->response($this->error('', 'REQUEST_ID'));
        }
        $goods_browse_model = new HotelBrowseModel();
        $res = $goods_browse_model->bathDeleteBrowse($id, $token[ 'data' ][ 'member_id' ]);
        return $this->response($res);
    }

    /**
     * 分页列表
     */
    public function page()
    {
        $token = $this->checkToken();
        if ($token[ 'code' ] < 0) return $this->response($token);

        $page = isset($this->params[ 'page' ]) ? $this->params[ 'page' ] : 1;
        $page_size = isset($this->params[ 'page_size' ]) ? $this->params[ 'page_size' ] : PAGE_LIST_ROWS;
        $lat = isset($this->params[ 'lat' ]) ? $this->params[ 'lat' ] : ""; // 纬度
        $lng = isset($this->params[ 'lng' ]) ? $this->params[ 'lng' ] : ""; // 经度
        $goods_browse_model = new HotelBrowseModel();
        $condition = [
            [ 'ngb.member_id', '=', $token[ 'data' ][ 'member_id' ] ]
        ];

        $field = 'ngb.id,ngb.member_id,ngb.browse_time,ngb.hotel_id,h.hotel_name,h.hotel_img,h.direct,h.full_address,h.address,h.longitude,h.latitude,h.label_format';
        $alias = 'ngb';
        $join = [
            ['hotel h', 'ngb.hotel_id = h.hotel_id', 'inner'],
        ];

        $list = $goods_browse_model->getBrowsePageList($condition, $page, $page_size, 'ngb.browse_time desc', $field, $alias, $join);

        if (!empty($list[ 'data' ][ 'list' ])) {
            foreach ($list[ 'data' ][ 'list' ] as $k => $item) {

                if ($item[ 'longitude' ] && $item[ 'latitude' ] && $lng && $lat) {
                    $list[ 'data' ][ 'list' ][ $k ][ 'distance' ] = round(getDistance((float) $item[ 'longitude' ], (float) $item[ 'latitude' ], (float) $lng, (float) $lat));
                } else {
                    $list[ 'data' ][ 'list' ][ $k ][ 'distance' ] = 0;
                }
            }
        }
        return $this->response($list);
    }
}